package com.akino.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Akino
 * @version 1.0
 * feign的配置
 */
@Configuration
public class GuliFeignConfig {
    // 添加拦截器
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 获取刚进来的请求数据
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes!=null) {
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        // 同步请求头数据（同步cookie）
                        template.header("Cookie", request.getHeader("Cookie"));
                    }
                }
            }
        };
    }
}
